// 子窗口组件
import { Button } from "antd";
import { useEffect } from "react";
const CommunicateTab = () => {
  // 发送消息给父窗口
  const sendToParent = (data) => {
    window.opener?.postMessage(
      { type: 'CHILD_RESPONSE', payload: data },
      '*'
    );
  };

  // 接收父窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      if (e.data.type === 'INIT_DATA') {
        console.log('父窗口初始化数据:', e.data.data);
      } else if (e.data.type === 'PARENT_COMMAND') {
        console.log('父窗口命令:', e.data.command);
        if (e.data.command === 'refreshData') {
          // 执行刷新操作
          sendToParent({ status: 'refreshed', time: new Date() });
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return (
    <div>
      <h3>可通信的子标签页</h3>
      <Button onClick={() => sendToParent({ message: '来自子窗口的消息' })}>
        发送消息给父窗口
      </Button>
    </div>
  );
};
export default CommunicateTab;